'use strict';
const { verifyJwt, loginResponse } = require('auth-token');
const { Z_TREES } = require('zlib');
exports.main = async (event, context) => {
  // 需登录才能访问
  const payload = verifyJwt(event.token)
  if (!payload) {
    return loginResponse()
  }
  const currentUid = payload._id
  
  // 数据库连接
  const dbJQL = uniCloud.databaseForJQL({event, context})
  dbJQL.setUser({ // 指定后续执行操作的用户信息，此虚拟用户将同时拥有传入的uid、role、permission
    uid: 'currentUid', // 用户id
    role: [], // 指定当前执行用户的角色为admin。如果只希望指定为admin身份，可以删除uid和permission字段
    permission: ["auth.uid == doc.user_id"] // 用户权限
  })
  const billCollection = dbJQL.collection('ledger-bill')
  
  // console.log('currentUid : ', currentUid)
  // 业务
  let message = ''
  switch (event.action) {
    case 'createBill':
     // 创建一个账单
     let bill = event.bill_data
		 const bTime = new Date(bill.bill_time)
		 const year = bTime.getFullYear().toString()
		 const month = (bTime.getMonth() + 1).toString().padStart(2, '0')
		 const date = (bTime.getDate()).toString().padStart(2, '0')
     const createBillRes = await billCollection.add({
       money: bill.money,
       bill_time: bill.bill_time,
       ledger_id: bill.ledger_id,
       bill_name: bill.bill_name,
       note: bill.note,
       user_id: currentUid,
			 year: year,
			 month: `${year}-${month}`,
			 bill_date:`${year}-${month}-${date}`,
     })
     if (createBillRes.id) {
       return {
         message: '创建账单成功!',
         _id: createBillRes.id
       }
     } else {
       return {
         message: createBillRes.errMsg,
         _id: undefined
       }
     }
     break
    case 'getBill': 
      // 查询一个账单
      const billId = event.bill_id
      if (!billId) {
        return {
          error: true,
          message: '参数错误，需提供ID!',
        }
      }
      const billRes = await billCollection.where(`_id=='${billId}'`).limit(1).get();
      // console.log('查询到账单对象：', billRes.data)
      if (billRes.data.length > 0) {
        return {
          bill: billRes.data[0],
          message: '查询账务条目成功!'
        }
      }
      break;
    case 'updateBill':
      // 更新一个账单
      const upBilldata = event.bill_data
      await billCollection.doc(upBilldata._id).update({
        bill_time: upBilldata.bill_time,
        money: upBilldata.money,
        ledger_id: upBilldata.ledger_id,
        bill_name: upBilldata.bill_name,
        note: upBilldata.note
      })
      return {
        _id: upBilldata._id,
        message: '更新成功!'
      }
      break;
    case 'delBill':
      // 删除一个账单
      const delBillId = event._id
      if (!delBillId) {
        return {
          error: true,
          message: '参数错误，无法定位条目!'
        }
      }
      await billCollection.doc(delBillId).remove()
      return {
        _id: '',
        message: '删除成功!'
      }
      break
    case 'getDateBill':
      // 查询某日账单
      const datets = event.date_timestamp
      if (!datets) {
        return {
          error: true,
          message: '参数错误，需提供时间戳!',
        }
      }
      const qDate = new Date(datets)
      const dateStartts = new Date(qDate.getFullYear(), qDate.getMonth(), qDate.getDate()).getTime()
      const dateEndts = dateStartts + 24 * 60 * 60 * 1000 - 1
      const dateBillRes = await billCollection.where(`bill_time>=${dateStartts} && bill_time <= ${dateEndts} && user_id=='${currentUid}'`).get()
      return {
        message: '查询日账单成功!',
        bills: dateBillRes.data
      }
      break;
    case 'getMonthBill':
      // 查询某月账单
      const monthts = event.date_timestamp
      if (!monthts) {
        return {
          error: true,
          message: '参数错误，需提供时间戳!',
        }
      }
      const dt = new Date(monthts)
      const monthsts = new Date(dt.getFullYear(), dt.getMonth(), 1).getTime()
      const monthets = new Date(dt.getFullYear(), dt.getMonth() + 1, 1).getTime() - 1
      const monthBillRes = await billCollection.where(`bill_time>=${monthsts} && bill_time <= ${monthets} && user_id=='${currentUid}'`).get()
      return {
        message: '查询月账单成功!',
        bills: monthBillRes.data
      }
      break;
    case 'getRangeBill':
      // 查询某期间[内的某分类]账单
      const rangests = event.start_timestamp
      const rangeets = event.end_timestamp
            const rangeledger = event.ledger_id
      if (!rangests || !rangeets) {
        return {
          error: true,
          message: '参数错误，请提供区间时间戳!'
        }
      }
            let qSql = `bill_time>=${rangests} && bill_time <= ${rangeets} && user_id=='${currentUid}'`
            if (rangeledger) {
                qSql += ` && ledger_id=='${rangeledger}'`
            }
      const rangeBillRes = await billCollection.where(qSql).get()
            
      return {
        message: '查询区间账单成功!',
        bills: rangeBillRes.data
      }
      break;
    case 'getRangeLedgerPage':
			// 查询某类期间内的分页账单
			const tsStart = event.start_ts
			const tsEnd = event.end_ts
			const ledgerId = event.ledger_id
			const page = event.page || 1
			const pageSize = event.size || 20
			if (!tsStart || !tsEnd || !ledgerId) {
				return {
					error: true,
					message: '参数错误，请提供区间时间戳和分类ID!'
				}
			}
			const skip = (page - 1) * pageSize
			
			let qlSql = `bill_time>=${tsStart} && bill_time <= ${tsEnd} && user_id=='${currentUid}' && ledger_id=='${ledgerId}'`
			const queryBillRes = await billCollection.where(qlSql).skip(skip).limit(pageSize).get()
			return {
				message: '查询区间分类账单成功!',
				bills: queryBillRes.data,
					page: page,
					size: pageSize
			}
			break;
    case 'statBill':
      // 按日期统计
      const dateStartTs = event.start_ts
      const dateEndTs = event.end_ts
      const statType = event.stat_type
			// 原来的统计方式，支付宝云服务不支持，其还未修复
      // 查询日期期间的，然后统计dateToString(add(new Date(0),register_date),"%Y-%m-%d","+0800") as date'
      // const groupByStr = `dateToString(add(new Date(0),bill_time),"${statType}","+0800") as name`
      // console.log('开始执行统计', groupByStr)
    //   const dateBillStatRes = await billCollection
				// .where(`bill_time>=${dateStartTs} && bill_time <= ${dateEndTs} && user_id=='${currentUid}'`)
				// .groupBy(groupByStr)
				// .groupField('sum(money) as totalMoney')
				// .get()
			
			let groupByColumn = 'year';
			if (statType == '%Y-%m') {
				groupByColumn = 'month'
			}
			if (statType == '%Y-%m-%d') {
				groupByColumn = 'bill_date'
			}

			const dateBillStatRes = await billCollection
				.where(`bill_time>=${dateStartTs} && bill_time <= ${dateEndTs} && user_id=='${currentUid}'`)
				.groupBy(groupByColumn)
				.groupField('sum(money) as totalMoney')
				.get()
      console.log('数据库统计结束:', dateBillStatRes)
			const statData = dateBillStatRes.data.map(item => {
				item['name'] = item[groupByColumn]
				return item
			})
      return {
        message: '账务统计成功!',
        data: statData
      }
      break;
        case 'cateStateBill':
            // 按类型统计
            const cateStartTs = event.start_ts
            const cateEndTs = event.end_ts
            // 查询分类数据
            const ledgerRes = await dbJQL.collection('ume-ledger').where(`user_id=='${currentUid}' || user_id==''`).field('_id,category_name,parent_id').get({getTree: true});
            const sumRes = await billCollection.where(`bill_time>=${cateStartTs} && bill_time <= ${cateEndTs} && user_id=='${currentUid}'`)
            .groupBy(`ledger_id`).groupField('sum(money) as totalMoney').get()
            const ledgerData = ledgerRes.data
            const sumData = sumRes.data
            // console.log('ledgerData', ledgerData)
            // console.log('sumData', sumData)
            sumData.forEach(item => {
                console.log('sumData', item)
                for(let i=0;i<ledgerData.length;i++) {
                    let isFind = false
                    let ledger = ledgerData[i]
                    ledger.total = ledger.total ? ledger.total : 0
                    // 目前只支持2层，无需递归
                    for(let j=0;j<ledger.children.length;j++) {
                        let child = ledger.children[j]
                        child.total = child.total ? child.total : 0
                        if (item.ledger_id == child._id) {
                            ledger.total += item.totalMoney
                            child.total += item.totalMoney
                            isFind = true
                        }
                    }
                    if (isFind) {
                        break;
                    }
                }
            })
            return {
                message: '分类统计成功!',
                data: {
                    ledgerStat: ledgerData,
                    // 2: sumData
                }
            }
            break;
    default:
        return {
          error: true,
          message: '参数错误!'
        }
      break;
  }
};
